import { NextFunction, Request, Response, Router } from "express";
import { BaseRoute } from "./route";
import * as login from '../sdk/openApi/login'
//import * as sms from '../sdk/psp/sms'
import * as sms from '../sdk/openApi/sms'
import * as salesOutlet from '../sdk/openApi/salesOutlet'
import * as register from '../sdk/openApi/register'
import * as order from '../sdk/openApi/order'
import * as policy from '../sdk/openApi/policy'
import * as voucher from '../sdk/openApi/voucher'
import * as orderDetail from '../sdk/openApi/orderDetail'
import * as payPlat from '../sdk/openApi/pay'
import * as productList from '../sdk/openApi/productList'
import * as goods from '../sdk/openApi/goods'
import * as region from '../sdk/openApi/region'
import * as paymentList from '../sdk/openApi/paymentChannels'
import Pay from "./pay"
import config from '../config'
import * as rsaKey from '../sdk/openApi/rsaKey'
import { GoodsRst } from "../sdk/openApi/goods";
import * as promotion from '../sdk/openApi/promotionInfo'
import * as bindingReferral from '../sdk/openApi/bindingReferral'
import * as touristOrder from '../sdk/openApi/touristOrder'
import * as touristPay from '../sdk/openApi/touristPay'
import * as getConfig from '../sdk/openApi/getConfig'
import * as allowDis from '../sdk/openApi/allowDiscount'
import * as discountAmnout from '../sdk/openApi/getDiscountAmnout'
import * as allowPromotionVoucher from '../sdk/openApi/allowPromotionVoucher'
import * as getUserVoucherByCode from '../sdk/openApi/getUserVoucherByCode'

/**
 * / route
 *
 * @class User
 */
export class ApiRoute extends BaseRoute {

  /**
   * Create the routes.
   *
   * @class IndexRoute
   * @method create
   * @static
   */
  public static create(router: Router) {
    //log
    console.log("Creating api route.");

    //add home page route
    router.get("/api", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().index(req, res, next);
    });

    router.post("/api/login", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().login(req, res, next);
    });

    router.post("/api/voucher", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().voucher(req, res, next);
    });

    router.post("/api/sms", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().sms(req, res, next);
    });

    router.post("/api/store", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().store(req, res, next);
    });

    router.post("/api/register", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().register(req, res, next);
    });

    router.post("/api/order", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().order(req, res, next);
    });

    router.post("/api/policy", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().policy(req, res, next);
    });

    router.post("/api/payPlat", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().payPlat(req, res, next);
    });

    router.post("/api/getProductList", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getProductList(req, res, next);
    });

    router.post("/api/getGoods", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getGoods(req, res, next);
    });

    router.post("/api/getRegion", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getRegion(req, res, next);
    });

    router.get("/api/index", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().index(req, res, next);
    });
    router.post("/api/getPaymentList", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getPaymentList(req, res, next);
    });

    router.post("/pay/result", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().result(req, res, next);
    });

    router.post("/api/promotionInfo", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().promotionInfo(req, res, next);
    });

    router.get("/api/getPublicKey", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getPublicKey(req, res);
    });

    router.post("/api/addTourist", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().addTouristInfo(req, res, next);
    });

    router.post("/api/touristPayPlat", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().touristPayPlat(req, res, next);
    });

    router.post("/api/getConfig", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getConfig(req, res, next);
    });

    router.post("/api/getDiscountAmnout", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getDiscountAmnout(req, res, next);
    });

    router.post("/api/allowPromotionVoucher", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().allowPromotionVoucher(req, res, next);
    });

    router.post("/api/getUserVoucherByCode", (req: Request, res: Response, next: NextFunction) => {
      new ApiRoute().getUserVoucherByCode(req, res, next);
    });
  }

  /**
   * 获取公钥
   */
  public async getPublicKey(req: Request, res: Response) {
    req.session.destroy((err) => {
    })
    const key = (await rsaKey.exec()).resData.publicKey;
    res.send(key)
  }

  /**
   * 获取配置信息
   */
  public async getConfig(req: Request, res: Response, next: NextFunction) {

    const configInfo = new getConfig.GetConfigRst();
    configInfo.ConfigKey = 'WhetherOpenH5NonMemberPayConfig'
    let result = await getConfig.exec(configInfo)

    res.send(result)
  }

  /**
   * The home page route.
   *
   * @class IndexRoute
   * @method index
   * @param req {Request} The express Request object.
   * @param res {Response} The express Response object.
   * @next {NextFunction} Execute the next method.
   */
  public index(req: Request, res: Response, next: NextFunction) {
    const pay = new Pay()
    pay.amount = 0.01;
    pay.orderNo = "005201708041548781234"
    pay.backUrl = 'http://localhost:8080';
    // res.send(pay.getPayUrl())
    res.redirect(pay.getPayUrl());
  }

  /**
   * 登录
   * @param req 
   * @param res 
   * @param next 
   */
  public async login(req: Request, res: Response, next: NextFunction) {
    if (req.session.user) {
      req.session.user = null
      req.session.loginParams = null
    }
    let loginRst = new login.loginRst();
    const loginParams = req.session.loginParams
    const request = req.body
    if (loginParams) {
      //注册成功后登录、设置session
      await this.sleep(1000); //暂停一秒再登录，数据库同步有点问题
      loginRst.loginInfo = '1\t' + loginParams.loginInfo.mobile + '\t' + loginParams.loginInfo.password + '\t';
      loginRst.deviceIdentity = loginParams.deviceIdentity;
      loginRst.clientSource = loginParams.clientSource;
      if (config.openApi.enableRSA) {
        loginRst.loginInfo = loginParams.rsaLogin;
      }
      /*const result = await login.exec(loginRst);
      if (result.resData) {
        req.session.user = result.resData;
        res.send(result.code);
      }else{
        res.send(result);
      } */
    } else if (request) {
      // loginRst.loginInfo = '1\t' + request.mobile + '\t' + request.password + '\t';
      loginRst.loginInfo = request.loginForm
      loginRst.deviceIdentity = request.deviceIdentity;
      loginRst.clientSource = request.clientSource;
      if (config.openApi.enableRSA) {
        loginRst.loginInfo = request.rsaLogin;
      }
    } else {
      res.send('获取不到用户登录信息');
      return false
    }
    // console.log(loginRst)
    const result = await login.exec(loginRst);
    // console.log('login-result',result)
    req.session.loginParams = null
    if (result.resData) {
      req.session.user = result.resData;
      res.send(result.code);
    } else {
      res.send(result);
    }
  }

  /**
   * 获取消费者代金券列表
   * 废弃，通过sku/user/bindingReferralUserByQuickPaymentScavenging 接口获取
   */
  public async voucher(req: Request, res: Response, next: NextFunction) {
    const user = req.session.user
    let bindResult = false
    let msg = { error: "", data: {}, mobile: user['mobile'], gw: user.code, isShow: false };
    if (!req.session.newRegister) { //旧用户
      //没有绑定推荐关系的，绑定注册关系
      const bindRst = new bindingReferral.BindingReferralRst();
      const salesOutlet = req.session.salesOutlet as salesOutlet.SalesOutletRpn;
      bindRst.salesOutletUID = salesOutlet.salesOutletUID;
      let rts = await bindingReferral.exec(bindRst, user);
      bindResult = rts.resData
      //console.log('bindResult:',bindResult,rts)
      //bindResult 为true代表现在操作已绑定 为false 不做处理
    }
    req.session.newRegister = false;

    if (user) {
      //查询当前的优惠金额
      const voucherRst = new voucher.VoucherRst();
      voucherRst.consumerUID = user.uid
      voucherRst.voucherStatus = [2]
      voucherRst.pageIndex = 1
      voucherRst.pageSize = 100

      let result = await voucher.exec(voucherRst, req.session.user)
      const totalCount = result.resData.list.length
      //console.log( result.resData,'list.length:',result.resData.list.length,'totalCount:',totalCount)
      if (totalCount > 0) {
        //console.log('bindResult:',bindResult,'req.session.newRegister:',req.session.newRegister)
        if (bindResult || req.session.newRegister) { msg.isShow = true }
        msg.data = { "status": 1000, "voucher": result.resData.list }
      } else {
        if (bindResult) {
          msg.isShow = true
        } else {
          msg.error = '获取代金券失败'
        }
      }
    }
    // console.log('msg:',msg)
    res.send(msg);
  }

  /**
    * 发短信
    * @param req 
    * @param res 
    * @param next 
    */
  public async sms(req: Request, res: Response, next: NextFunction) {
    const currentTime = Date.now();
    if (req.session.lastTime && (currentTime - req.session.lastTime < 60000)) {
      res.send('60秒内只能发送一次短信');
    }

    const rst = new sms.SmsRst();
    rst.mobile = req.body.mobile;
    rst.type = 1;
    const data = await sms.exec(rst);
    req.session.lastTime = Date.now();
    res.send(data);
  }
  /**
    * 店铺信息
    * @param req 
    * @param res 
    * @param next 
    */
  public async store(req: Request, res: Response, next: NextFunction) {
    req.session.user = ''
    const rst = new salesOutlet.SalesOutletRst();
    rst.salesOutletUID = req.body.suid;
    const result = await salesOutlet.exec(rst);
    const msg = { error: "", data: {}, resData: {} };
    if (result.resData) {
      const status = result.resData.status
      if (status == salesOutlet.SalesOutletStatus.apply) {
        msg.error = "该门店正在申请中"
      } else if (status == salesOutlet.SalesOutletStatus.disable) {
        msg.error = "该门店已经被禁用"
      } else {
        let salesOutlet = result.resData;
        msg.resData = salesOutlet;
        msg.data = {
          gw: salesOutlet.merchantCode,
          salesOutletName: salesOutlet.name,
          storeUID: salesOutlet.storeUID,
          publicKey: config.openApi.enableRSA ? (await rsaKey.exec()).resData.publicKey : ''
        };
        req.session.salesOutlet = result.resData;
      }
    } else {
      msg.error = "查询不到门店，请重试"
    }
    res.send(msg);
  }

  /**
   * 注册
   * @param req 
   * @param res 
   * @param next 
   */
  public async register(req: Request, res: Response, next: NextFunction) {
    if (!req.body) return false;
    const rst = new register.RegisterRst();
    rst.registInfo = req.body.mobile + '\t' + req.body.password + '\t' + req.body.checkCode + '\t' + req.body.referralCode + '\t' + req.body.registMethod + '\t' + req.body.salesOutletUID;
    if (config.openApi.enableRSA) {
      rst.registInfo = req.body.rsaRegister;
    }
    const data = await register.exec(rst);
    if (data.isSuccess && data.resData) {
      //req.session.loginInfo = { mobile: req.body.mobile, password: req.body.password }
      req.session.loginParams = {
        loginInfo: { mobile: req.body.mobile, password: req.body.password },
        deviceIdentity: req.body.deviceIdentity,
        clientSource: req.body.clientSource,
        rsaLogin: req.body.rsaLogin
      }
      req.session.newRegister = true;
    }
    res.send(data);
  }

  public async order(req: Request, res: Response, next: NextFunction) {
    const rst = new order.OrderRst();
    let info = req.session.salesOutlet as salesOutlet.SalesOutletRpn;
    rst.userUID = req.session.user.uid;
    rst.storeUID = info.storeUID;
    rst.salesOutletUID = info.salesOutletUID;

    const orderInfo = req.body;

    rst.amount = parseFloat(orderInfo.amount);
    rst.noDiscountPrice = orderInfo.noDiscountPrice;
    rst.totalPrice = orderInfo.totalPrice;
    rst.remark = orderInfo.remark;
    rst.clientSource = 1;
    if (orderInfo.voucherUID) {
      rst.voucherUID = orderInfo.voucherUID
      rst.voucherAmount = parseFloat(orderInfo.voucherAmount)
      rst.voucherType = orderInfo.voucherType
      rst.amount += rst.voucherAmount
      rst.amount = parseFloat(rst.amount.toFixed(2))
    }


    //console.log(rst,orderInfo)
    const data = await order.exec(rst, req.session.user);
    /* const payInfo = { payUrl: "", msg: "查询结果" };
    if (data.isSuccess && data.resData) {
      const detailRst = new orderDetail.OrderDetailRst();
      detailRst.salesOrderUID = data.resData;
      const detail = await orderDetail.exec(detailRst, req.session.user);
      const pay = new Pay();
      if (detail.resData) {
        pay.orderNo = detail.resData.salesOrderCode;
        pay.amount = orderInfo.amount;
        pay.backUrl = config.domain + '/pay/result';
        pay.product_name = info.name + "-快捷支付";
        const payUrl = pay.getPayUrl();
        payInfo.payUrl = payUrl;
      } else {
        payInfo.msg = "获取订单编号出错无法跳转到支付页面";
      }
    }else{
      payInfo.msg = data.description
    }
    res.send(payInfo); */

    //2017-12-15使用支付平台接口支付
    let orderMsg = { status: 0, msg: "" }
    if (data.isSuccess && data.resData) {
      orderMsg.status = 1
      orderMsg.msg = '下单成功'
      const detailRst = new orderDetail.OrderDetailRst();
      detailRst.salesOrderUID = data.resData;
      req.session.salesOrderUID = data.resData;
      const detail = await orderDetail.exec(detailRst, req.session.user);
      if (detail.resData) {
        req.session.salesOrderCode = detail.resData.salesOrderCode
      } else {
        orderMsg.msg = '下单成功，获取订单号失败，无法支付'
      }
    } else {
      orderMsg.status = 0
      orderMsg.msg = data.description
    }
    res.send(orderMsg)
  }

  /**
   * 获取优惠信息
   * @param req
   * @param res 
   * @param next 
   */
  public async policy(req: Request, res: Response, next: NextFunction) {
    const rst = new policy.PolicyRst();
    const salesOutlet = req.session.salesOutlet as salesOutlet.SalesOutletRpn;
    const user = req.session.user;
    rst.salesOutletUID = salesOutlet.salesOutletUID;
    const result = await policy.exec(rst, user);

    const msg = {
      error: "",
      data: policy.PolicyRpn.prototype,
      currencySymbol: "",
      promotion: salesOutlet.promotionData,
      mobile: user.mobile,
      gw: user.code
    };
    msg.currencySymbol = user.currencySymbol
    if (result.resData) {
      msg.data = result.resData;
    } else {
      msg.error = "该门店没有优惠信息"
    }
    res.send(msg);
  }
  /**
   * 支付前端回调地址 // 高汇通
   * @param req 
   * @param res 
   * @param next 
   */
  public async result(req: Request, res: Response, next: NextFunction) {
    //判断支付结果
    let pay = new Pay()
    let result = pay.verifyPayresult(req.query) //true or false
    console.log(JSON.stringify(req.query));
    console.log(JSON.stringify(req.body));
    res.redirect(config.domain + "/#/result/?pay=" + result)
  }

  /**
   * 支付提交
   */
  public async payPlat(req: Request, res: Response, next: NextFunction) {
    let rst = new payPlat.PayRst();
    const payInfo = req.body
    rst.merchantType = payInfo.merchantType
    rst.clientType = 3
    rst.paymentType = payInfo.paymentType
    rst.paymentMethod = payInfo.paymentMethod
    rst.returnUrl = payInfo.returnUrl
    rst.salesOrderCode = req.session.salesOrderCode
    rst.remark = payInfo.remark
    rst.clientIP = payInfo.clientIP
    rst.wapUrl = payInfo.wapUrl

    const data = await payPlat.exec(rst, req.session.user)
    res.send(data)
  }

  /**
   * 
   * 获取门店商品列表
   * @param req 
   * @param res 
   * @param next 
   */
  public async getProductList(req: Request, res: Response, next: NextFunction) {
    let rst = new productList.ProductListRst();
    const params = req.body
    rst.pageIndex = 1
    rst.pageSize = 5
    rst.productStatus = 3
    rst.salesOutletUID = params.salesOrderUID
    rst.returnFields = ["id", "productUID", "name", "supplyPrice", "productPictures"]
    const data = await productList.exec(rst);
    res.send(data)
  }

  public async getGoods(req: Request, res: Response, next: NextFunction) {
    let rst = new goods.GoodsRst();
    rst.productUID = req.body.productUID
    rst.returnFields = ["productUID", "name", "supplyPrice", "productPictures", "description"]
    const data = await goods.exec(rst);
    res.send(data)
  }

  public async getRegion(req: Request, res: Response, next: NextFunction) {
    const data = await region.exec(new region.RegionRst());
    res.send(data)
  }

  public async getPaymentList(req: Request, res: Response, next: NextFunction) {
    const payment = new paymentList.res();
    payment.payAmount = req.body.payAmount;
    const data = await paymentList.exec(payment);
    res.send(data);

  }

  /**
   * 获取活动信息
   * @param req 
   * @param res 
   * @param next 
   */
  public async promotionInfo(req: Request, res: Response, next: NextFunction) {
    const data = await promotion.exec(req.body.uid);
    res.send(data);
  }

  /**
   * 游客下单
   * @param req 
   * @param res 
   * @param next 
   */
  public async addTouristInfo(req: Request, res: Response, next: NextFunction) {
    const tourist = new touristOrder.touristOrderRst();
    let request = req.body
    tourist.amount = request.amount;
    tourist.salesOutletUID = request.salesOutletUID;
    tourist.storeUID = request.storeUID;
    tourist.noDiscountPrice = request.noDiscountPrice;
    tourist.totalPrice = request.totalPrice;
    tourist.remark = request.remark;
    tourist.clientSource = request.clientSource || 1;
    // console.log('reqreqreq',req.body)

    const data = await touristOrder.exec(tourist);
    //console.log('data::',data)
    res.send(data);
  }

  /**
   * 
   * @param req 游客下单预支付
   * @param res 
   * @param next 
   */
  public async touristPayPlat(req: Request, res: Response, next: NextFunction) {
    let rst = new touristPay.TouristPayRst();
    const payInfo = req.body
    rst.merchantType = payInfo.merchantType
    rst.clientType = 3
    rst.paymentType = payInfo.paymentType
    rst.returnUrl = payInfo.returnUrl
    rst.salesOrderCode = payInfo.salesOrderCode
    rst.remark = payInfo.remark
    rst.clientIP = payInfo.clientIP
    rst.wapUrl = payInfo.wapUrl
    rst.sign = await touristPay.SingMD5(rst.salesOrderCode)
    //console.log('Request',rst)
    let data = await touristPay.exec(rst)
    // data.isSuccess = 1;
    // data.code = "1000";
    // data.description = "请求成功";
    // data.resData.tokenID = '';
    // data.resData.linkUrl = "";
    // data.resData.aliApiJson = "";
    // data.resData.jsApiJson = "";
    // data.resData.paymentCode = '00520180730173314818';
    // data.resData.aliHtml = "<form id='alipaysubmit' name='alipaysubmit' action='https://openapi.alipay.com/gateway.do?charset=UTF-8' method='POST' style='display:none;'><input  name='app_id' value='2017111509948366'/><input  name='biz_content' value='{\"body\":\"壹键哥订单-005201807302502523\",\"out_trade_no\":\"00520180730173425820\",\"product_code\":\"QUICK_WAP_PAY\",\"subject\":\"壹键哥订单-005201807302502523\",\"timeout_express\":\"5m\",\"total_amount\":\"0.01\"}'/><input  name='charset' value='UTF-8'/><input  name='format' value='json'/><input  name='method' value='alipay.trade.wap.pay'/><input  name='notify_url' value='https://testskuapi.g-emall.com/sku/paymentPlatform/aliAppPayCallbackNotify'/><input  name='return_url' value='http://skupay.gwemall.com/#/touristPayResult?salesOrderCode=005201807302502523&amount=0.01&storeName=椰风园&pay=支付宝支付&businessCategoryName=KTV'/><input  name='sign_type' value='RSA2'/><input  name='timestamp' value='2018-07-30 17:34:25'/><input  name='version' value='1.0'/><input  name='sign' value='E11NnsVCg0S5kIKVLk95aMaPbJSPgoDH7Hq91/4TeFRdLhUTShaG2Qk+yMJlvaDGgFAHfs6yZP9liFQeLNTE+ZDzonoHKpMd+oYRlQfj49u3Fcb11E1uWhSKnJOsTFbGsWf6Re/UUhXwQcjJY2/2qOqc4QxSLthKO1CPVNoBjAJMuudIysjsPTfoI2Z1urXkXa/6v7A03ORkJ4nudAmicFqjqY7PJKiBC7ZOfoNCNxqpdFc2l5PG39QBBYoznqG9t0oRkBDYIg87L7dbCW9srylptPdcRX/XVqrbvzCCEa+/8OfadcAu+uhE7nEXa2G4OOFScnmCSCURoUhdejCOZw=='/><input type='submit' value='POST' style='display:none;'></form><script>document.forms['alipaysubmit'].submit();</script>";

    res.send(data)
  }


  /**
  * 
  * @param req 根据订单唯一id获取支付随机满减金额 请求方式
  * @param res 
  * @param next 
  */
  public async getDiscountAmnout(req: Request, res: Response, next: NextFunction) {
    const _model = new allowDis.AllowDiscountRst();
    const user = req.session.user;
    _model.salesOrderUID = req.session.salesOrderUID;
    const result = await allowDis.exec(_model, user);

    let rtnData = { isAllow: result.resData, data: { hasDiscountAmount: false, discountAmount: 0, type: 0, isShow: false, h5RealDiscount: 0 } }
    if (result.isSuccess == 1 && result.resData) {
      //请求满减的金额
      const discountRts = new discountAmnout.DiscountAmnoutRst();
      discountRts.salesOrderUID = req.session.salesOrderUID;
      let rtn = await discountAmnout.exec(discountRts, user);
      if (rtn.code == '1000') rtnData.data = rtn.resData
    }
    res.send(rtnData);
  }

  /**
   * 
   * @param req H5页面是否允许是有活动代金券
   * @param res 
   * @param next 
   */
  public async allowPromotionVoucher(req: Request, res: Response, next: NextFunction) {
    const user = req.session.user;
    const _model = await allowPromotionVoucher.exec(user)
    res.send(_model)
  }

  /**
   * 
   * @param req 检测用户登录是否有代金券
   * @param res 
   * @param next 
   */
  public async getUserVoucherByCode(req: Request, res: Response, next: NextFunction) {
    const user = req.session.user;
    const _model = new getUserVoucherByCode.GetUserVoucherByCodeRst();
    _model.userCode = user.code;

    let result = await getUserVoucherByCode.exec(_model, user);
    // console.log('result:',result);
    res.send(result)
  }

}